package com.lmabbe.oauth.granter.authentication;

import com.lmabbe.common.global.context.session.JwtUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;

/**
 * 提供短信验证码校验逻辑的类
 *
 * @author lmabbe
 * @data 2021/5/11 20:35
 */
@Slf4j
public class SmsVerificationCodeAuthenticationProvider implements AuthenticationProvider {

    /**
     * 得到UserDetailsService对象用来获取用户信息
     */
    private UserDetailsService userDetailsService;

    public void setUserDetailsService(UserDetailsService userDetailsService) {
        this.userDetailsService = userDetailsService;
    }

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        SmsVerificationCodeAuthenticationToken authenticationToken = (SmsVerificationCodeAuthenticationToken) authentication;
        log.info("进行短信身份验证的逻辑");
        log.info("(JSONObject) authenticationToken.getPrincipal()===>" + authenticationToken.getPrincipal());
        JwtUser user = (JwtUser) userDetailsService.loadUserByUsername("12");

        /*if( authenticationToken.getPrincipal().toString().equals("100")) {
            throw new InternalAuthenticationServiceException("无法获取用户信息");
           }
        */

        SmsVerificationCodeAuthenticationToken smsVerificationCodeAuthenticationToken = new SmsVerificationCodeAuthenticationToken(user, user.getAuthorities());
        smsVerificationCodeAuthenticationToken.setDetails(authenticationToken.getDetails());
        return smsVerificationCodeAuthenticationToken;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        // 判断authentication是否是SmsCodeAuthenticationToken类型
        return SmsVerificationCodeAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
